﻿/*----------------------------------------------------------------
    // Copyright (C) 2009 江苏华招网
    // 版权所有。 
    // 作者：马毅 
    //
    // 文件名：DistributionRelationByCom.cs
    // 文件功能描述：按地区查看配送关系
    // 创建标识：马毅2009-05-18
    //
    // 修改标识：
    // 修改描述：
    //
    // 修改标识：
    // 修改描述：
    //
    // 审核人：
// 审核时间：
// 审核说明：
 //----------------------------------------------------------------*/
using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using HZ.DrugTrade.IBLL;
using HZ.DrugTrade.BLLFactory;
using HZ.DrugTrade.Model;
using System.Data;
using HZ.DrugTrade.Model.Enum;
namespace HZ.DrugTrade.Web.Enterprise.RelationQuery
{
    public partial class ProductCompanySubArea : BasePage
    {
        public ProductCompanySubArea()
        {
            this.ModuleNo = Module.分配送管理.ToString();
        }

        IBLL_Distribution id = Factory.BLL_Distribution();
        IBLL_ProcurementBasic ipb = Factory.BLL_ProcurementBasic();
        IBLL_SelectRelation iselectRelation = Factory.BLL_SelectRelation();

        string procureCatalogId = "";

        /// <summary>
        /// 是否能删除可配送
        /// </summary>
        public bool CanDel
        {
            get {return  iselectRelation.CheckCanDelRelation(CurrentAccount.GetUser().Org.OrgID); }
        }


        /// <summary>
        /// 是否能删除可配送
        /// </summary>
        public bool getCanDel(object Status, object Auditstatus)
        {
            bool r = ((Status.ToString() == "可配送" && CanDel) || (Status.ToString() != "可配送") || Auditstatus.ToString() == "审核未通过"); 
            
            return r;

        }


        protected void Page_Load(object sender, EventArgs e)
        {
            procureCatalogId = Request.QueryString["PID"];
            ViewState["v_procureCatalogId"] = procureCatalogId;
            ViewState["ProjectID"] = Request.QueryString["ProjectID"];


            if (!IsPostBack)
            {
                Model.View.ProcureCatalog procureCatalog = ipb.GetProcureCatalogByID(procureCatalogId);
                lblCompany_SC.Text = procureCatalog.CompanyName_SC;
                lblCompany_ZB.Text = procureCatalog.CompanyName_TB;
                lblGoodsName.Text = procureCatalog.GoodsName;
           
                lblOutlookc.Text = procureCatalog.Outlookc;
              

                Banding();//绑定
            }
        }
        /// <summary>
        /// 绑定可勾选的配送企业
        /// </summary>
        public void Bind()
        {
            HZ.DrugTrade.Model.Query.Company company = new HZ.DrugTrade.Model.Query.Company();
            if (!string.IsNullOrEmpty(txtCompanyName.Text.Trim().ToString()))
            {
                company.CompanyName = txtCompanyName.Text.Trim().ToString();
            }
            if (ViewState["ProjectID"].ToString() == "0001")
            {
                company.Append = string.Format(@"(CompanyType <>0 )  and CompanyID in (SELECT distinct CompanyPS_Id
  FROM TB_PSSelectArea where AreaID like '%{0}%'and checkByZbzx=1 and ishcygcg is null) and (ishcygcg is null or ishcygcg = 2) and companytype != 3  or companyid in (select companyid_ps from tb_company where companyid = '{1}')", this.GetAreaID(), CurrentAccount.GetUser().UserID);
            }
            else
            {
                company.Append = string.Format(@"(CompanyType <>0 )  and CompanyID in (SELECT distinct CompanyPS_Id
  FROM TB_PSSelectArea where AreaID like '%{0}%'and checkByZbzx=1 and ishcygcg = 1) and companytype != 3 and ishcygcg in(1,2) or companyid in (select companyid_ps from tb_company where companyid = '{1}')", this.GetAreaID(), CurrentAccount.GetUser().UserID);
            }
            AspNetPager2.PageSize = 10;
            int totalRecord = 0;
            IBLL_Company iPurchase = Factory.BLL_Company();
            IList<Company> lstcompany = iPurchase.GetCompanyByWhere(company, AspNetPager2.CurrentPageIndex, AspNetPager2.PageSize, out totalRecord);
            AspNetPager2.RecordCount = totalRecord;
            gvwProduceCatalogOne.DataSource = lstcompany;
            gvwProduceCatalogOne.DataBind();
        }
        /// <summary>
        /// 绑定
        /// </summary>
        private void Banding()
        {
            string strWhere = " ";
            string strAreaID=GetAreaID();
            if (string.IsNullOrEmpty(strAreaID) == false && strAreaID.EndsWith("0000")==false)
            {
                strWhere += " and AreaID='" + strAreaID + "'";
            }
            string Unioncitystateda = ddlauditstatus.SelectedItem.Value;
            if (!string.IsNullOrEmpty(Unioncitystateda))
            {
                if (Unioncitystateda == "0")
                {
                    strWhere += " and auditstatus = '未审核'";
                }
                else if (Unioncitystateda == "1")
                {
                    strWhere += " and auditstatus = '审核通过'";
                }
                else if (Unioncitystateda == "2")
                {
                    strWhere += " and auditstatus = '审核未通过'";
                }
            }
            strWhere += " and procureCatalogId='" + ViewState["v_procureCatalogId"].ToString() + "' order by ProcureCataLogID,areaID,companyID_PS";
            int totalCount = 0;
            AspNetPager1.PageSize = Constants.GRIDVIEW_PAGE_SIZE;
            DataTable dt = iselectRelation.GetSelectRelationByProcureCatalogID(strWhere, AspNetPager1.CurrentPageIndex, AspNetPager1.PageSize, out totalCount);
            gvwProduceCatalog.DataSource = dt;
            gvwProduceCatalog.DataBind();
            AspNetPager1.RecordCount = totalCount;
        }

        /// <summary>
        /// 获取默认选中的地区编号串
        /// </summary>
        /// <returns></returns>
        protected string GetDefaultAreaString()
        {
            //默认城市 江苏省 320000
            string defaultCity = "";
            string defaultProvince = "";

            Model.Area aArea = CurrentAccount.GetCurrentDeployArea();  //获取当前实施地区的地区

            defaultProvince = aArea.AreaID;

            string strArea = "";
            //显示默认地区
            strArea += "," + "\"" + defaultProvince + "\"";
            this.ddlProvice.Enabled = false;
            if (!string.IsNullOrEmpty(defaultCity))
            {
                strArea += "," + "\"" + defaultCity + "\"";
                this.ddlCity.Enabled = false;
            }
            else if (!string.IsNullOrEmpty(Request.Form["ctl00$ContentPlaceHolder1$ddlCity"]))
            {
                strArea += "," + "\"" + Request.Form["ctl00$ContentPlaceHolder1$ddlCity"] + "\"";
            }

            if (!string.IsNullOrEmpty(Request.Form["ctl00$ContentPlaceHolder1$ddlCountry"]))
            {
                strArea += "," + "\"" + Request.Form["ctl00$ContentPlaceHolder1$ddlCountry"] + "\"";
            }

            return strArea;
        }

        /// <summary>
        /// 选择配送企业
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSelectCompanyByAreaId_Click(object sender, EventArgs e)
        {

            Page.ClientScript.RegisterStartupScript(Page.GetType(), "SelectCompany", "window.open('CompanySelect.aspx?areaid=" + this.GetAreaID() + "','SelectCompany','width=600,height=450,resizable=0,scrollbars=0, status=0, toolbar=0, menubar=0');", true);
        }

        /// <summary>
        /// 保存地区和和企业
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void HzButton1_Click(object sender, EventArgs e)
        {
            HZ.DrugTrade.Model.SelectRelation selectRelation = new HZ.DrugTrade.Model.SelectRelation();
            selectRelation.ProcureCatalogID = ViewState["v_procureCatalogId"].ToString();
            selectRelation.CompanyID_TB = CurrentAccount.GetUser().Org.OrgID;
            string comType = HZ.DrugTrade.BLLFactory.Factory.BLL_Company().GetComType(CurrentAccount.GetUser().Org.OrgID);
            if (comType != "生产企业" && comType != "经营企业")
            {
                this.Controls.Add(new LiteralControl("<script>alert('无权操作');window.close();</script>"));
                return;
            }
            if (GetAreaID() == "150000")
            {
                this.Controls.Add(new LiteralControl("<script>alert('请选择配送区域,配送的区域不能为内蒙古自治区');window.close();</script>"));
                return;
            }
            else
            {
                selectRelation.AreaID = GetAreaID();
                int nResurt = 0;
                if (gvwProduceCatalogOne.Rows.Count > 0)
                {
                    for (int i = 0; i < gvwProduceCatalogOne.Rows.Count; i++)
                    {
                        CheckBox ckb = ((CheckBox)gvwProduceCatalogOne.Rows[i].FindControl("checkbox1"));
                        if (ckb.Checked == true)
                        {
                            selectRelation.CompanyID_PS = gvwProduceCatalogOne.DataKeys[i].Value.ToString();
                            nResurt = iselectRelation.AddSelectRelation(selectRelation, ViewState["ProjectID"].ToString());
                        }
                    }
                    //if (new HZ.Common.ConvertHelper(companyId.Value).String == "")
                    //{
                    //    HZ.Web.WebUtil.Alert("配送企业未选择！", this); return;
                    //}
                    //if (new HZ.Common.ConvertHelper(companyId.Value).String == CurrentAccount.GetUser().Org.OrgID)
                    //{
                    //    HZ.Web.WebUtil.Alert("不能添加本企业！", this); return;
                    //}
                    //selectRelation.CompanyID_PS = companyId.Value.Trim();




                    if (nResurt == 1)
                    {
                        HZ.Web.WebUtil.Alert("保存成功！", this);
                        //this.txtCompany.Text = "";
                        //this.companyId.Value = "";
                        //
                        Banding();
                    }
                    else if (nResurt == 2)
                    {
                        HZ.Web.WebUtil.Alert("已存在指定配送企业！", this);
                        //this.txtCompany.Text = "";
                        //this.companyId.Value = "";
                        //
                        Banding();
                    }
                    else if (nResurt == 5)
                    {
                        HZ.Web.WebUtil.Alert("该地区已达到指定配送企业最大数！", this);
                        //this.txtCompany.Text = "";
                        //this.companyId.Value = "";
                        //
                        Banding();
                    }
                    else if (nResurt == 6)
                    {
                        HZ.Web.WebUtil.Alert("选择的配送企业没有该区域的配送权限！", this);
                        Banding();
                    }
                    else
                    {
                        HZ.Web.WebUtil.Alert("数据异常！", this);
                        //this.txtCompany.Text = "";
                        //this.companyId.Value = "";
                    }
                }
                else
                {
                    HZ.Web.WebUtil.Alert("请至少选择一个配送企业！", this);
                    return;
                }
            }
        }
        /// <summary>
        /// 获取地区ID
        /// </summary>
        /// <returns></returns>
        private string GetAreaID()
        {
            string areaId = "";

            //首次进入使用系统部署所在区域ID
            Model.Area aArea = CurrentAccount.GetCurrentDeployArea();  //获取当前实施地区的地区
            areaId = aArea.AreaID;

            //优先获取城市，再次省份
            if (new Common.ConvertHelper(Request.Form["ctl00$ContentPlaceHolder1$ddlCity"]).String != Constants.ALL_ITEM_VALUE)
            {
                areaId = Request.Form["ctl00$ContentPlaceHolder1$ddlCity"];
            }
            else if (new Common.ConvertHelper(Request.Form["ctl00$ContentPlaceHolder1$ddlProvice"]).String != Constants.ALL_ITEM_VALUE)
            {
                areaId = Request.Form["ctl00$ContentPlaceHolder1$ddlProvice"];
            }
            
            return areaId;
        }

        protected void btn_Del(object sender, EventArgs e)
        {
            string comType = HZ.DrugTrade.BLLFactory.Factory.BLL_Company().GetComType(CurrentAccount.GetUser().Org.OrgID);
            if (comType != "生产企业" && comType != "经营企业")
            {
                this.Controls.Add(new LiteralControl("<script>alert('无权操作');window.close();</script>"));
                return;
            }
            HZ.Web.HzLinkButton btn = sender as HZ.Web.HzLinkButton;
            string str = btn.CommandArgument.ToString();
            string[] array = str.Split(',');

            HZ.DrugTrade.Model.SelectRelation aAreaDistribution = new HZ.DrugTrade.Model.SelectRelation();
            aAreaDistribution.ProcureCatalogID = array[0];
            aAreaDistribution.CompanyID_PS = array[1];
            aAreaDistribution.AreaID = array[2];


            if (!getCanDel(array[3], array[4]))
            {
                HZ.Web.WebUtil.Alert("无权限操作！", this);
                Page_Load(sender, e);

            }
           //   CASE WHEN [Status] = - 1 THEN '未提交' WHEN [Status] = 0 THEN '未确定' WHEN [Status] = 1 THEN '已同意' WHEN [Status] = 2 THEN '已拒绝' WHEN [Status] = 3 THEN    '可配送' END AS Status
            switch (array[3])
            {
                case "":
                case "未提交":
                    aAreaDistribution.Status = -1;
                    break;
                case "未确定":
                    aAreaDistribution.Status = 0;
                    break;
                case "已同意":
                    aAreaDistribution.Status = 1;
                    break;
                case "已拒绝":
                    aAreaDistribution.Status = 2;
                    break;
                case "可配送":
                    aAreaDistribution.Status = 3;
                    break;
                default:
                    break;
            }
            aAreaDistribution.CompanyID_TB = CurrentAccount.GetUser().Org.OrgID;//操作人
            int intReturn = iselectRelation.DeleteSelectRelation(aAreaDistribution);
            switch (intReturn)
            {
                case 0:
                    PageInfo("删除失败，请与服务中心联系！", Request.RawUrl);
                    break;
                case 1:
                    PageInfo("删除成功！", Request.RawUrl);
                    break;
                case 2:
                    PageInfo("该配送企业已在该地区发生配送业务，不能删除！", Request.RawUrl);
                    break;
            }
            

        }
        /// <summary>
        /// 绑定事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gvwProduceCatalog_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                HZ.Web.HzLinkButton btn = e.Row.FindControl("lbtnDel") as HZ.Web.HzLinkButton;
                HZ.DrugTrade.Model.SelectRelation item = e.Row.DataItem as HZ.DrugTrade.Model.SelectRelation;
                btn.CommandArgument = string.Format("{4},{3},{2},{1},{0}", this.gvwProduceCatalog.DataKeys[e.Row.RowIndex].Values["auditstatus"], this.gvwProduceCatalog.DataKeys[e.Row.RowIndex].Values["status"], this.gvwProduceCatalog.DataKeys[e.Row.RowIndex].Values["AreaID"], this.gvwProduceCatalog.DataKeys[e.Row.RowIndex].Values["CompanyID_PS"], this.gvwProduceCatalog.DataKeys[e.Row.RowIndex].Values["ProcureCatalogID"]);

                HZ.Web.HzLinkButton lbtnRequestDel = e.Row.FindControl("lbtnRequestDel") as HZ.Web.HzLinkButton;
                HZ.DrugTrade.Model.SelectRelation items = e.Row.DataItem as HZ.DrugTrade.Model.SelectRelation;
                lbtnRequestDel.CommandArgument = string.Format("{3},{2},{1},{0}", this.gvwProduceCatalog.DataKeys[e.Row.RowIndex].Values["status"], this.gvwProduceCatalog.DataKeys[e.Row.RowIndex].Values["AreaID"], this.gvwProduceCatalog.DataKeys[e.Row.RowIndex].Values["CompanyID_PS"], this.gvwProduceCatalog.DataKeys[e.Row.RowIndex].Values["ProcureCatalogID"]);

            }
        }

        protected void AspNetPager1_OnPageChanged(object sender, EventArgs e)
        {
            Banding();
        }

        protected void btnSelect_Click(object sender, EventArgs e)
        {
            this.AspNetPager1.CurrentPageIndex = 1;
            this.AspNetPager2.CurrentPageIndex = 1;
        }

        protected void Button1_Click(object sender, EventArgs e)
        {

        }

        protected void lbtnRequestDel_Click(object sender, EventArgs e)
        {
            HZ.Web.HzLinkButton btn = sender as HZ.Web.HzLinkButton;
            string str = btn.CommandArgument.ToString();
            string[] array = str.Split(',');

            HZ.DrugTrade.Model.SelectRelation aAreaDistribution = new HZ.DrugTrade.Model.SelectRelation();
            aAreaDistribution.ProcureCatalogID = array[0];
            aAreaDistribution.CompanyID_PS = array[1];
            aAreaDistribution.AreaID = array[2];
            int intReturn = iselectRelation.GetDelRequestDelete(aAreaDistribution);
            switch (intReturn)
            {
                case 0:
                    PageInfo("申请删除失败，请与服务中心联系！", Request.RawUrl);
                    break;
                case 1:
                    PageInfo("申请删除成功！", Request.RawUrl);
                    break;
            }
        }

        protected void AspNetPager2_PageChanged(object sender, EventArgs e)
        {
            Bind();
        }
        public string Getauditstatus(object auditstatus)
        {
            string auditstatuscol = "";
            switch (auditstatus.ToString())
            {
                case "未审核":
                    auditstatuscol = "<font color=black>未审核</font>";;
                    break;
                case "审核通过":
                    auditstatuscol = "<font color=blue>审核通过</font>"; ;
                    break;
                case "审核未通过":
                    auditstatuscol = "<font color=red>审核未通过</font>"; ;
                    break;
                default:
                    break;
            }
            return auditstatuscol;
        }
    }

}
